let functions=require("./datbase");

function countSameCommodity(collection){
    let result = [];
    let obj = {};
    for(let item of collection){
        if(/^[A-Z]{4}[0-9]{6}$/.test(item)){
            if(!obj[item]){
                obj[item] = 1;
            }else {
                obj[item] += 1;
            }
        }
        else{
            let num=parseInt(item.replace(/^[A-Z]{4}[0-9]{6}[-]/,""));
            item=item.replace(/[-][1-9]$/,"");
            if(!obj[item]){
                obj[item]=num;
            }
            else{
                obj[item]+=num;
            }
        }
    }
    for(let value in obj){
        result.push({barcode: value, count: obj[value]})
    }
    return result;
}


function addInformation(arr1,arr2){
    let result=[];
    for(let item1 of arr1){
        for(let item2 of arr2){
            if(item1.barcode==item2.barcode){
                result.push({barcode:item2.barcode, name:item2.name, unit:item2.unit, price:item2.price, count:item1.count});
                
            }
        }
    }
    return result;
}

function promotionCommodity(obj){
    let promotion=functions.loadPromotions()[0];
    for(let item of promotion.barcodes){
        if(obj.barcode==item){
            return true;
        }
    }
}

function printInventory(commodity,freeCommodity){
    let paymentSum=0;
    let freeSum=0;
    let result='***<没钱赚商店>购物清单***\n';
    for(let item of commodity){
        result+="名称："+item.name+"，数量："+item.count+item.unit+"，单价："+item.price.toFixed(2)+"(元)，小计："+item.subtotal.toFixed(2)+"(元)\n";
        paymentSum+=item.subtotal;
    }
    result+='----------------------\n' +
    '挥泪赠送商品：\n';
    for(let item of freeCommodity){
        result+="名称："+item.name+"，数量："+item.count+item.unit+"\n";
        freeSum+=item.subtotal;
    }
    result+='----------------------\n'+
    "总计："+paymentSum.toFixed(2)+"(元)\n"+
    "节省："+freeSum.toFixed(2)+"(元)\n"+
    '**********************';
    console.log(result);
    return result;
}

function main(inputs){
    function loadAllItems(){

    }
    let freeCommodity=[];
    let commodity =countSameCommodity(inputs);
    let allCommodity=functions.loadAllItems();
    commodity=addInformation(commodity,allCommodity);
    for(let item of commodity){
        if(promotionCommodity(item)){
            freeCommodity.push({
                    barcode:item.barcode, 
                    count:Math.floor(item.count/3),
                    name:item.name,
                    unit:item.unit,
                    price:item.price,
                    subtotal:item.price*(Math.floor(item.count/3))
                                })
            item.subtotal=(item.count-Math.floor(item.count/3))*item.price;
        }
        else{
            item.subtotal=item.count*item.price;
        }
    }
    let result= printInventory(commodity,freeCommodity);
    return result;

}
module.exports =main;

